package com.bangcommunity.bbframe.fdfs.connection;

import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.ProtoCommon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.Socket;

/**
 * @author tanghc
 * @date 18/6/22
 */
public class BaseFdfsSocketConnection implements FdfsSocketConnection {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    protected Socket socket;
    protected String host;
    protected Integer port;
    protected byte errno;

    public BaseFdfsSocketConnection(String host, Integer port) {
        this.host = host;
        this.port = port;
        initSocket();
    }

    public BaseFdfsSocketConnection(String address) {
        super();
        String[] hostport = address.split(":");
        this.host = hostport[0];
        this.port = Integer.valueOf(hostport[1]);
        initSocket();

    }
    private void initSocket(){
        try {
            getSocket();
        } catch (IOException e) {
            logger.warn("init socket fail when construct TrackerConnection");
        }
    }

    @Override
    public Socket getSocket() throws IOException {
        if (socket == null) {
            socket = ClientGlobal.getSocket(host, port);
        }
        return socket;
    }



    @Override
    public boolean isClosed() throws IOException {
        if (null == socket) {
            return true;
        }
        if (this.socket.isClosed()) {
            return true;
        }
        return !ProtoCommon.activeTest(this.getSocket());
    }

    @Override
    public void close() throws IOException {
        if (null != this.socket) {
            ProtoCommon.closeSocket(this.socket);
        }
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }
}
